package com.cas.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.DeliveryMode;

@Configuration
public class JmsMessagingTemplateConfig {

    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;

    @Value("${spring.activemq.user}")
    private String user;

    @Value("${spring.activemq.password}")
    private String password;

    @Value("${spring.activemq.packages.trust-all}")
    private boolean trustAll;

    @Value("${spring.jms.pub-sub-domain}")
    private boolean pubSubDomain;

    @Value("${spring.jms.template.delivery-mode}")
    private String persistent;


    @Bean("jmsMessagingTemplatePro")
    @Scope("prototype")
    public JmsMessagingTemplate jmsMessagingTemplatePro() {
        JmsMessagingTemplate jmsMessagingTemplate = new JmsMessagingTemplate();
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
        activeMQConnectionFactory.setBrokerURL(brokerUrl);
        activeMQConnectionFactory.setUserName(user);
        activeMQConnectionFactory.setPassword(password);
        activeMQConnectionFactory.setTrustAllPackages(trustAll);
        jmsMessagingTemplate.setConnectionFactory(activeMQConnectionFactory);
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setPubSubDomain(pubSubDomain);
        if (persistent==null || persistent.isEmpty()){
            jmsTemplate.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }else {
            jmsTemplate.setDeliveryMode(DeliveryMode.PERSISTENT);
        }
//        jmsTemplate.setMessageConverter(jacksonJmsMessageConverter());
        jmsMessagingTemplate.afterPropertiesSet();
        return jmsMessagingTemplate;
    }

//    @Bean
//    public MappingJackson2MessageConverter jacksonJmsMessageConverter() {
//        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
//        converter.setTargetType(MessageType.TEXT);
//        converter.setTypeIdPropertyName("_type");
//        return converter;
//    }
}
